package com.mc.fastkit.widget

import android.os.CountDownTimer
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

/**
 * CountDownHelper
 * @author: MasterChan
 * @date: 2023/10/20 11:27
 */
class CountDownHelper(lifecycleOwner: LifecycleOwner) {

    private var countDownTimer: CountDownTimer? = null
    private var totalMillis = 0L
    private var stepMillis = 0L
    private var onTick: ((Long) -> Unit)? = null
    private var onFinish: (() -> Unit)? = null

    init {
        lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                countDownTimer?.cancel()
            }
        })
    }

    fun setMillis(totalMillis: Long, stepMillis: Long = 1000) = apply {
        this.totalMillis = totalMillis
        this.stepMillis = stepMillis
    }

    fun doOnTick(onTick: (Long) -> Unit) = apply { this.onTick = onTick }

    fun doOnFinish(onFinish: (() -> Unit)) = apply { this.onFinish = onFinish }

    fun start() {
        countDownTimer = object : CountDownTimer(totalMillis, stepMillis) {
            override fun onTick(millisUntilFinished: Long) {
                onTick?.invoke(millisUntilFinished)
            }

            override fun onFinish() {
                onFinish?.invoke()
            }
        }
        countDownTimer!!.start()
    }

    fun cancel() {
        countDownTimer?.cancel()
    }
}